package com.wangku.springmvc.utils.redis;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.io.IOException;
import java.util.Properties;

/**
 * @description: redis 连接池工具类
 * @author: 李赛赛
 * @create: 2018-07-11 11:37
 **/
public class RedisPoolUtil {

    private static JedisPool jedisPool = null;
    private static String redisConfigFile = "redis.properties";

    //把redis连接对象放到本地线程中`
    private static ThreadLocal<Jedis> local=new ThreadLocal<Jedis>();
    //不允许通过new创建该类的实例
    private RedisPoolUtil() {
    }

    static int i = 0;
    /**
     * 初始化Redis连接池
     */
    public static void initialPool(){

        try {
            //加载连接池配置文件
            Properties props = new Properties();
            props.load(RedisPoolUtil.class.getClassLoader().getResourceAsStream(redisConfigFile));
            // 创建jedis池配置实例
            JedisPoolConfig config = new JedisPoolConfig();
            // 设置池配置项值
            config.setMaxTotal(Integer.valueOf(props.getProperty("redis.maxTotal")));//最大链接数
            config.setMaxIdle(Integer.valueOf(props.getProperty("redis.maxIdle")));//最大空闲连接数
            config.setMaxWaitMillis(Long.valueOf(props.getProperty("redis.maxWaitMillis")));
            config.setTestOnBorrow(Boolean.valueOf(props.getProperty("redis.testOnBorrow")));
            config.setTestOnReturn(Boolean.valueOf(props.getProperty("redis.testOnReturn")));
            config.setTimeBetweenEvictionRunsMillis(10000);//释放连接的扫描间隔（毫秒）
            config.setNumTestsPerEvictionRun(1024);//每次释放连接的最大数目

            // 根据配置实例化jedis池
            jedisPool = new JedisPool(config,props.getProperty("redis.host"),Integer.valueOf(props.getProperty("redis.port")),
                    Integer.valueOf(props.getProperty("redis.timeout")));
            i = i + 1;
            System.out.println("线程池被成功初始化"+i);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * @description  获取redis 连接
     * @date 2018/7/11 13:10
     * @param
     * @return   Jedis
     */
    public synchronized static Jedis getConnect(){
//        获取当前线程jedis连接
        Jedis jedis = local.get();
        if (jedis == null) {
            if (jedis == null) {
                initialPool();
            }
            jedis = jedisPool.getResource();
            local.set(jedis);
        }
        return jedis;
    }
    /**
     * @description 关闭redis 连接
     * @date 2018/7/11 13:17
     * @param
     * @return
     */
    public static void closeConnect(){
        Jedis jedis = local.get();
        if (jedis != null) {
            jedis.close();
        }
        local.set(null);
    }
    /**
     * @description  关闭池
     * @date 2018/7/11 13:21
     * @param
     * @return
     */
    public static void closePool(){
        if(jedisPool!=null){
            jedisPool.close();
        }
    }


}
